//
//  GYLogger.m
//  GYLogger
//
//  Created by APPLE on 2020/6/23.
//  Copyright © 2020 APPLE. All rights reserved.
//

#import "GYLogger.h"
#import <CocoaLumberjack.h>
#import "GYLoggerFormater.h"

static GYLogger * _logger;

@interface GYLogger ()
@property (nonatomic, strong) GYLoggerFormater * formatter;
@end

@implementation GYLogger
+ (instancetype) shareInstance {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _logger = [[GYLogger alloc] init];
    });
    return _logger;
}

- (instancetype)init {
    self = [super init];
    if (self) {
       if (@available(iOS 10.0, macOS 10.12, tvOS 10.0, watchOS 3.0, *)) {
           _OSLogger = DDOSLogger.sharedInstance;
           [DDLog addLogger:_OSLogger];
       } else {
           _TTYLogger = DDTTYLogger.sharedInstance;
           [DDLog addLogger:_TTYLogger];
       }
    }
    return self;
}

- (void)setFilelogger:(DDFileLogger *)filelogger {
    if (_filelogger != filelogger) {
        _filelogger = filelogger;
        [DDLog addLogger:_filelogger];
    }
}


- (void) log:(BOOL)asynchronous
   formatter:(BOOL)simpleFormat
       level:(DDLogLevel)level
        flag:(DDLogFlag)flag
     context:(NSInteger)context
        file:(nonnull const char *)file
    function:(nullable const char *)function
        line:(NSUInteger)line
         tag:(nullable id)tag
      format:(nonnull NSString *)format, ...{
    if (simpleFormat) {
        if (self.filelogger) {
            self.filelogger.logFormatter = self.formatter;
        }
        
        if (self.OSLogger) {
            self.OSLogger.logFormatter = self.formatter;
        }
        
        if (self.TTYLogger) {
            self.TTYLogger.logFormatter = self.formatter;
        }
    } else {
        self.filelogger.logFormatter = nil;
        self.OSLogger.logFormatter = nil;
        self.TTYLogger.logFormatter = nil;
    }
}

- (GYLoggerFormater *)formatter {
    if (!_formatter) {
        _formatter = [[GYLoggerFormater alloc] init];
    }
    return _formatter;
}

- (void)setSimpleFormate:(BOOL)simpleFormate {
    if (_simpleFormate != simpleFormate) {
        _simpleFormate = simpleFormate;
        self.OSLogger.logFormatter = _simpleFormate ? nil : self.formatter;
        self.TTYLogger.logFormatter = _simpleFormate ? nil : self.formatter;
    }
}


@end
